<template>
  <Modal
      :title="modalProps.title"
      :show="modalProps.show"
      @ok="handleOk"
      @cancel="handleCancel"
  >
    <ModalForm ref="form"></ModalForm>
  </Modal>
</template>

<script lang="ts">
export default {
  name: "BrandModal"
}
</script>

<script setup lang="ts">
import Modal from '@/components/Modal.vue'
import ModalForm from '@/components/ModalForm.vue'
import { reactive, ref} from 'vue'
import {FormModalType} from '@/type/ModalFormType'
import {BrandSaveFormType, BrandSaveType, BrandUpdateType} from '@/view/shopping/brand/brandType'
import {ums_brand_save, ums_brand_update, ums_category_queryList, ums_category_treeList} from '@/api/sms'
import useMsg from '@/hooks/useMsg'
import {categoryListType} from '@/view/shopping/category/category'
import {treeNode} from '@/utils'

const {success, error} = useMsg()

const modalProps = reactive<{
  title: string
  show: boolean
  type: 0|1
}>({
  title: "",
  show: false,
  type: 0
})

const emit = defineEmits<{
  (e: 'list'):void
}>()

const form = ref<FormModalType<BrandSaveFormType>>()

const formData = ref<BrandUpdateType>()

const init = (data?: BrandUpdateType) => {
  modalProps.show = true
  if (data) {
    modalProps.title = "编辑"
    modalProps.type = 1
    formData.value = data
  } else {
    modalProps.title = "添加"
    modalProps.type = 0
  }
  ums_category_treeList().then(res => {

    form.value?.init([
      {
        type: "input",
        key: "brand_name",
        label: "品牌名称",
        value: data?.brand_name
      },
      {
        type: "tree",
        key: "category_id",
        label: "分类名称",
        value: data?.category_id,
        treeOptions: res.data.map(item => treeNode<categoryListType>(item, {
          label: 'category_name',
          key: "category_id"
        })),
        multiple: modalProps.type === 1 ? false : true
      },
    ])
  })
}

const handleOk = () => {
  form.value?.validate().then(data => {

    if (modalProps.type === 0) {
      const obj:BrandSaveType = {
        category_id: Array.isArray(data.category_id) && data.category_id.join(','),
        brand_name: data.brand_name
      }
      ums_brand_save( obj ).then( res => {
        if (res.code === 200) {
          success( res.message )
          modalProps.show = false
          emit( "list" )
        } else {
          error( res.message )
        }
      })
    }
    if (modalProps.type === 1) {
      ums_brand_update({
        category_id: data.category_id as string,
        brand_name: data.brand_name,
        brand_id: formData.value!.brand_id
      }).then(res => {
        if (res.code === 200) {
          success( res.message )
          modalProps.show = false
          emit( "list" )
        } else {
          error( res.message )
        }
      })
    }
  })
}

const handleCancel = () => {
  modalProps.show = false
}

defineExpose({
  init
})

</script>

<style scoped lang="scss">

</style>
